﻿/*
Copyright (c) 2010, hiSoft
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the hiSoft nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE HISOFT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL HISOFT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;

namespace Orchard.Test.Library
{
    public class PageHelper : UIHelperBase
    {
        public ContentItemHelper ContentItemHelper;

        public PageHelper(TestLibrary settings)
            : base(settings)
        {
            ContentItemHelper = new ContentItemHelper(settings);
        }
       
        private void InputPageSetting(PageSettings pageSetting)
        {
            if (selenium.IsElementPresent("Containable_ContainerId") && pageSetting.ContainerId != null)
            {
                selenium.Select("Containable_ContainerId", String.Format("List: {0}", pageSetting.ContainerId.Title));
            }

            selenium.Type("Routable_Title", pageSetting.Title);
            selenium.Type("Routable_Slug", pageSetting.Permalink);
            if (pageSetting.SetAsHomePage)
            {
                selenium.Check("Routable_PromoteToHomePage");
            }
            else
            {
                selenium.Uncheck("Routable_PromoteToHomePage");
            }

            if (pageSetting.OnMainMenu)
            {
                selenium.Check("OnMainMenu");
                selenium.Type("MenuText", pageSetting.MenuText);
            }
            else
            {
                selenium.Uncheck("OnMainMenu");
            }

            if (pageSetting.Tags!=null && pageSetting.Tags.Count!=0)
            {
                string tagsString = null;
                for (int i = 0; i < pageSetting.Tags.Count; i++)
                {
                    tagsString += pageSetting.Tags[i].Name + ",";
                }
                selenium.Type("Tags_Tags", tagsString);
            }

            if (selenium.IsElementPresent("CommentsActive"))
            {
                if (pageSetting.AllowNewComments)
                {
                    selenium.Check("CommentsActive");
                }
                else
                {
                    selenium.Uncheck("CommentsActive");
                }
            }

            if (pageSetting.Owner != TestLibrary.Consts.AdminUserName)
            {
                selenium.Type(OwnerLocator, pageSetting.Owner);
            }

            if (pageSetting.ArchiveLater)
            {
                selenium.Check("ArchiveLater_Command_ArchiveLater"); 
                if(!string.IsNullOrEmpty(pageSetting.ArchiveDate))
                selenium.Type("ArchiveLater_ScheduledArchiveDate", pageSetting.ArchiveDate);
                if (!string.IsNullOrEmpty(pageSetting.ArchiveTime))
                selenium.Type("ArchiveLater_ScheduledArchiveTime", pageSetting.ArchiveTime);           
            }
            if (pageSetting.PublishSetting == PublishSettings.None)
            {
                return;
            }
            switch (pageSetting.PublishSetting)
            {                
                case PublishSettings.SaveDraft:
                    ClickAndWait("//button[@value='submit.Save']");
                    break;
                case PublishSettings.PublishNow:
                    ClickAndWait("//button[@value='submit.Publish']");
                    break;
                case PublishSettings.PublishLater: 
                    selenium.Type("PublishLater_ScheduledPublishDate", pageSetting.PublishDate);
                    selenium.Type("PublishLater_ScheduledPublishTime", pageSetting.PublishTime);                 
                    ClickAndWait("//button[@value='submit.PublishLater']");
                    break;
            }
           
            pageSetting.Permalink = selenium.GetValue("Routable_Slug");
            string[] idStrs = selenium.GetLocation().Split('/');
            int pageId = -1;
            Int32.TryParse(idStrs[idStrs.Length - 1], out pageId);
            pageSetting.Id = pageId;
        }

        public Page CreateRandomPage()
        {
            return CreatePage(new PageSettings());
        }

        public Page CreatePage(PageSettings pageSetting)
        {
            selenium.Open("/Admin/Contents/Create/Page");
            InputPageSetting(pageSetting);
            var page = new Page(pageSetting);
            string editPageUrl = selenium.GetLocation();
            string[] pageIdStrings = editPageUrl.Split('/');
            int pageId=0;
            Int32.TryParse(pageIdStrings[pageIdStrings.Length-1], out pageId);
            page.Id = pageId;
            return page;           
        }       
       
        public Page EditPage(Page page, PageSettings newSetting)
        {
            ContentItemHelper.DoActionToContentItem(page, ContentItemAction.Edit);
            InputPageSetting(newSetting);
            return new Page(newSetting);              
        }

        public Page CreateDraftForPublishedPage(Page page, PageSettings newSetting)
        {         
            newSetting.PublishSetting = PublishSettings.SaveDraft;
            return EditPage(page, newSetting);
        }

        public void DiscardDraftOfPublishedPage(Page page)
        {
            ContentItemHelper.DoActionToContentItem(page, ContentItemAction.Edit);           
            ClickAndWait("link=Discard Draft");            
        }     

        public string GetPublishStatusOfPage(Page page)
        {
            int index = ContentItemHelper.GetContentItemIndexOnManageContents(page);
            string publishStatusString = selenium.GetText(String.Format("{0}[{1}]/div/div/div/ul/li[1]", ContentItemsLocator, index));
            return publishStatusString.Substring(0,publishStatusString.Length-2);
        }

        public string GetDraftStatusOfPage(Page page)
        {
            int index = ContentItemHelper.GetContentItemIndexOnManageContents(page);
            string draftStatusString = selenium.GetText(String.Format("{0}[{1}]/div/div/div/ul/li[2]", ContentItemsLocator, index));
            return draftStatusString.Substring(0, draftStatusString.Length - 2);
        }

        public string GetOwnerOfPage(Page page)
        {
            int index = ContentItemHelper.GetContentItemIndexOnManageContents(page);
            string ownerString = selenium.GetText(String.Format("{0}[{1}]/div/div/div/ul[2]/li[2]", ContentItemsLocator, index));
            string[] ownerStrings = ownerString.Split(' ');
            return ownerStrings[1];
        }

        public string GetPublishDateTimeOnViewPage(Page page)
        {
            selenium.Open("/" + page.Permalink);
            return selenium.GetText("//div[@id='content']/div/div/article/header/div/div");
        }
       
        public void ChangePageSlug(Page page,string newSlug)
        {
            ContentItemHelper.DoActionToContentItem(page, ContentItemAction.Edit);
            selenium.Type("Routable_Slug", newSlug);
            ClickAndWait("//button[@value='submit.Publish']");
        }        

        public Page TranslatePage(Page page, string language)
        {
            return TranslatePage(page, language, PublishSettings.PublishNow);
        }

        public Page TranslatePage(Page page, string language, PublishSettings publishAction)
        {
            int index = ContentItemHelper.GetContentItemIndexOnManageContents(page);
            ClickAndWait(String.Format("{0}[{1}]/div/div[3]/div/div/a", ContentItemsLocator, index));
            if (!String.IsNullOrEmpty(language))
            {
                selenium.Select("SelectedCulture", String.Format("label={0}", language));
            }
            var routableTitle = String.Format("{0} {1} {2}", page.Title, language, GenerateUniqueIdentifier());
            selenium.Type("Routable_Title", routableTitle);
            string permalink = String.Format("{0}-{1}-{2}", page.Permalink, language, GenerateUniqueIdentifier());
            selenium.Type("Routable_Slug", permalink);
            if (publishAction == PublishSettings.PublishNow)
            {
                ClickAndWait("//button[@value='submit.Publish']");
            }
            else if (publishAction == PublishSettings.SaveDraft)
            {
                ClickAndWait("//button[@value='submit.Save']");
            }
            var pageSettings = new PageSettings();
            pageSettings.Title = routableTitle;
            pageSettings.Permalink = permalink;
            var translatedPage = new Page(pageSettings);
            return translatedPage;
        }

        public string EditOtherPageByLanguageLink(Page page, string language)
        {
            int index = ContentItemHelper.GetContentItemIndexOnManageContents(page);
            var languagesCount = (int)selenium.GetXpathCount(String.Format("{0}[{1}]/div/div[3]/div/div[1]/ul/li", ContentItemsLocator, index));
            for (int i = 1; i <= languagesCount; i++)
            {
                string languageLocator = String.Format("{0}[{1}]/div/div[3]/div/div[1]/ul/li[{2}]/a", ContentItemsLocator, index, i);
                if (selenium.GetText(languageLocator) == language)
                {
                    ClickAndWait(languageLocator);
                    break;
                }
            }
            return selenium.GetLocation();
        }

        public void ChangeBodyFlavorOfPage(string flavor)
        {
            selenium.Open("/Admin/ContentTypes/Edit/Page");
            selenium.Click("//fieldset[@itemid='BodyPart']/h3/span/span");
            selenium.Type("//fieldset[@itemid='BodyPart']/div[2]/div/fieldset/input", flavor);
            Submit(); 
        }
    }

    public class PageSettings : ContentItemSettings
    {
        public Lists ContainerId { get; set; }

        public bool OnMainMenu { get; set; }

        public string MenuText { get; set; }

        public string Body { get; set; }

        public List<Tag> Tags { get; set; }

        public bool AllowNewComments { get; set; }        

        public PublishSettings PublishSetting { get; set; }

        public string PublishDate { get; set; }

        public string PublishTime { get; set; }

        public bool ArchiveLater { get; set; }

        public string ArchiveDate { get; set; }

        public string ArchiveTime { get; set; }

        public PageSettings()
        {
            string uniqueIdentifier = UIHelperBase.GenerateUniqueIdentifier(DateTime.Now);
            Title = String.Format("Page {0}", uniqueIdentifier);
            Permalink = String.Format("page-{0}", uniqueIdentifier);
            PublishSetting = PublishSettings.PublishNow;
            AllowNewComments = true;
            Owner = TestLibrary.Consts.AdminUserName;
        }

        public PageSettings(bool autoGeneratePermalink)
        {
            Title = String.Format("Page {0}", UIHelperBase.GenerateUniqueIdentifier(DateTime.Now));
            if (!autoGeneratePermalink)
            {
                Permalink = String.Format("page-{0}", UIHelperBase.GenerateUniqueIdentifier(DateTime.Now));
            }            
            PublishSetting = PublishSettings.PublishNow;
            Owner = TestLibrary.Consts.AdminUserName;
        }
    }

    public class Page : ContentItem, IContent
    {
        public PageSettings PageSetting { get; private set; }

        public string MenuText { get { return PageSetting.MenuText; } }

        public List<Tag> Tags { get { return PageSetting.Tags; } }

        public Page(PageSettings pageSetting)
        {
            PageSetting = pageSetting;
            Title = pageSetting.Title;
            Permalink = pageSetting.Permalink;
            Owner = pageSetting.Owner;
        }
    }
}
